package com.example.controller;

import com.example.entity.Product;
import com.example.entity.User;
import com.example.service.ProductService;
import com.example.service.LikeService;
import com.example.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    
    @Autowired
    private LikeService likeService;
    
    @Autowired
    private CartService cartService;

    // 搜索页面
    @GetMapping("/search")
    public String searchPage(@RequestParam(required = false) String keyword, Model model, HttpSession session) {
        // 获取所有商品，如果没有关键字就显示全部
        List<Product> products;
        if (keyword != null && !keyword.trim().isEmpty()) {
            products = productService.searchProducts(keyword);
        } else {
            products = productService.getAllProducts();
        }
        model.addAttribute("products", products);
        
        // 获取用户的点赞和购物车状态
        User user = (User) session.getAttribute("user");
        if (user != null) {
            // 获取用户点赞的商品ID集合
            Set<Long> likedProductIds = likeService.getUserLikedProductIds(user.getId());
            model.addAttribute("likedProductIds", likedProductIds);
            
            // 获取用户购物车中的商品ID集合
            Set<Long> cartProductIds = cartService.getUserCartProductIds(user.getId());
            model.addAttribute("cartProductIds", cartProductIds);
        }
        
        model.addAttribute("isLoggedIn", user != null);
        model.addAttribute("keyword", keyword);
        
        return "product/search";
    }

    // 商品详情页面
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Long id, Model model, HttpSession session) {
        Product product = productService.getProductById(id);
        if (product == null) {
            // 如果商品不存在，重定向到搜索页面
            return "redirect:/product/search";
        }
        model.addAttribute("product", product);
        
        // 获取当前用户的点赞状态
        User user = (User) session.getAttribute("user");
        boolean hasLiked = false;
        if (user != null) {
            hasLiked = likeService.hasLiked(user.getId(), id);
        }
        model.addAttribute("hasLiked", hasLiked);
        model.addAttribute("isLoggedIn", user != null);
        
        return "product/detail";
    }
} 